package com.cxka.payment.service.impl;

import cn.hutool.json.JSONUtil;
import com.cxka.common.constant.CS;
import com.cxka.common.result.ReqResult;
import com.cxka.common.util.EncodeUtils;
import com.cxka.common.util.HttpUtils;
import com.cxka.common.util.Md5Utils;
import com.cxka.common.util.SignUtils;
import com.cxka.payment.domain.dto.CreateOrderDTO;
import com.cxka.payment.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Service
public class PaymentServiceImpl implements PaymentService {

    /**
     * 创建订单
     *
     * @return
     */
    @Override
    public boolean createOrder(CreateOrderDTO dto) {

        // 1、校验参数 @NotNull注解参数完成此步骤
        // 2、生成签名、参数
        Map map = structure(dto);
        // 3、发送请求
        String res = HttpUtils.sendPost(CS.REQUEST_URL, map);
        ReqResult reqResult = JSONUtil.toBean(res, ReqResult.class);
        // 4、处理订单
        if (CS.SUCCESS_NO == reqResult.getErr_no() && CS.SUCCESS_STATUS == reqResult.getResults().getStatus()) {
            log.info("创建订单成功，单号：{}", dto.getOrder_id());
            // 更新订单状态，返回支付链接
            return true;
        } else {
            log.error("创建订单失败，单号：{}", dto.getOrder_id());
            /**
             * 多版本编码转换
             */
            log.error("错误信息：{}", EncodeUtils.decodeUnicode(reqResult.getResults().getError()));
        }

        return false;
    }

    /**
     * 构造参数
     *
     * @param dto
     * @return
     */
    private Map structure(CreateOrderDTO dto) {

        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        /**
         * value替换为所需要的值，此处仅作示例
         */
        map.put("app_key", "app_key");
        map.put("api_domain", "l6.com");
        map.put("goods_id", "2");
        map.put("goods_num", "1");
        map.put("order_id", "202012061934001");
        map.put("is_mobile", "1");
        map.put("key", "ApI-Secret");
        String preSignContent = SignUtils.getPreSignContent(map);
        log.info("文档比对   = app_key=app_key&api_domain=api_domain&goods_id=goods_id&goods_num=goods_num&order_id=order_id&is_mobile=is_mobile&key=key");
        log.info("preSignContent = {}", preSignContent);
        String md5 = null;
        try {
            md5 = Md5Utils.md5(preSignContent);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        map.put("contact", "15221027573");
        map.put("callback_url", "http://www.16ss.com/notify");
        map.put("ip_address", "127.0.0.1");
        map.put("pay_type", "0");
        map.put("sign", md5);
        map.put("discount_price", "0.5");
        return map;
    }
}
